package xyz.liuz.edb;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;

public class ServiceServerHandler extends SimpleChannelInboundHandler<String> {
    private int lossConnectCount  = 0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        lossConnectCount = 0;//计数器清零
        System.out.println(msg);
//        System.out.println(new Date());
//        Thread.sleep(5000);
//        System.out.println(new Date());
        String returnF5Msg = "EDBHEARTBEAT";
        ctx.write(returnF5Msg);
        ctx.flush();

        String nodeId="hello";
        AttributeKey<String> nodeIdAttrKey = AttributeKey.valueOf("NODE_ID");
        ctx.channel().attr(nodeIdAttrKey).set(nodeId);
        System.out.println(ctx.channel().attr(nodeIdAttrKey).get());

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("已经好久没有收到客户端的消息了");
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            System.out.println(event.state()+":::::"+ IdleState.READER_IDLE);
            if (event.state() == IdleState.READER_IDLE){
                lossConnectCount++;
                if (lossConnectCount>2){
                    System.out.println("关闭这个不活跃的通道:"+ctx.channel().remoteAddress());
                    ctx.channel().close();
                }
            }

        }else{
            System.out.println("这是个啥");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        System.out.println("客户端主机（" + ctx.channel().remoteAddress() + "）异常报错"+ cause);
        ctx.close();
    }
}
